// 打开或创建 IndexedDB 数据库
const openDB = () => {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open('BackgroundDB', 1);

        request.onupgradeneeded = (event) => {
            const db = event.target.result;
            if (!db.objectStoreNames.contains('background')) {
                db.createObjectStore('background', { keyPath: 'id' });
            }
        };

        request.onsuccess = (event) => {
            resolve(event.target.result);
        };

        request.onerror = (event) => {
            reject('IndexedDB 打开失败');
        };
    });
};

// 保存文件到 IndexedDB
const saveFileToDB = async (file, type) => {
    const db = await openDB();
    const transaction = db.transaction('background', 'readwrite');
    const store = transaction.objectStore('background');
    const request = store.put({ id: 'background-file', file, type });

    return new Promise((resolve, reject) => {
        request.onsuccess = () => resolve();
        request.onerror = () => reject('保存文件失败');
    });
};

// 从 IndexedDB 读取文件
const readFileFromDB = async () => {
    const db = await openDB();
    const transaction = db.transaction('background', 'readonly');
    const store = transaction.objectStore('background');
    const request = store.get('background-file');

    return new Promise((resolve, reject) => {
        request.onsuccess = () => resolve(request.result ? request.result : null);
        request.onerror = () => reject('读取文件失败');
    });
};

// 获取元素
const backimgButton = document.getElementById('backimg');
const backgroundVideo = document.getElementById('background-video');

// 页面加载时检查是否有保存的背景文件
(async () => {
    const result = await readFileFromDB();
    if (result) {
        const fileURL = URL.createObjectURL(result.file);
        if (result.type === 'video') {
            backgroundVideo.src = fileURL;
        } else if (result.type === 'image') {
            document.body.style.backgroundImage = `url(${fileURL})`;
        }
    }
})();

// 监听按钮点击事件
backimgButton.addEventListener('click', () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*, video/mp4'; // 允许选择图片和视频
    input.onchange = async (event) => {
        const file = event.target.files[0];
        if (file) {
            const type = file.type.startsWith('video') ? 'video' : 'image';
            await saveFileToDB(file, type); // 保存文件到 IndexedDB
            const fileURL = URL.createObjectURL(file);
            if (type === 'video') {
                backgroundVideo.src = fileURL;
                document.body.style.backgroundImage = '';
            } else {
                document.body.style.backgroundImage = `url(${fileURL})`;
                backgroundVideo.src = '';
            }
        }
    };
    input.click(); // 触发文件选择框
});